package nuc98x

import (
	"fmt"
	"golang.org/x/sys/unix"
	gtime "openzbox.com/utils/time"
	"os"
	"syscall"
	"time"
)

var rtcNumber = 0

/*
	从网络时间服务器同步系统时间
*/
func SyncRtcTimeFromInternet() error {
	err := gtime.SyncTimeFromNTP()
	if err != nil {
		return err
	}
	return nil
}

func ReadDateTime() (rtctime time.Time, err error) {
	// Use the devfs path for now instead of sysfs path.
	f, err := os.Open(fmt.Sprintf("/dev/rtc%d", rtcNumber))
	defer f.Close()
	errt := time.Date(int(0), time.Month(0), int(0), int(0), int(0), int(0), 0, time.UTC)

	if err != nil {
		if os.IsNotExist(err) {
			return errt, fmt.Errorf("/dev/rtc%d is not configured.", rtcNumber)
		}
		// TODO(maruel): This is a debianism.
		return errt, fmt.Errorf("sysfs-rtc: are you member of group 'plugdev'? %v", err)
	}
	rt, err := unix.IoctlGetRTCTime(int(f.Fd()))
	t := time.Date(int(rt.Year+1900), time.Month(int(rt.Mon)+1), int(rt.Mday), int(rt.Hour), int(rt.Min), int(rt.Sec), 0, time.UTC)
	//fmt.Printf("RTC time: %04d-%02d-%02d %02d:%02d:%02d", v.Year+1900, v.Mon+1, v.Mday, v.Hour, v.Min, v.Sec)
	return t, nil
}

func SetDateTime(t time.Time) error {

	//fmt.Printf("RTC time: %04d-%02d-%02d %02d:%02d:%02d", v.Year+1900, v.Mon+1, v.Mday, v.Hour, v.Min, v.Sec)
	// Use the devfs path for now instead of sysfs path.
	f, err := os.Open(fmt.Sprintf("/dev/rtc%d", rtcNumber))
	defer f.Close()
	//errt:=time.Date(int(0), time.Month(0), int(0), int(0), int(0), int(0), 0, time.UTC)
	if err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("/dev/rtc%d is not configured.", rtcNumber)
		}
		// TODO(maruel): This is a debianism.
		return fmt.Errorf("sysfs-rtc: are you member of group 'plugdev'? %v", err)
	}
	rtctime := &unix.RTCTime{}
	rtctime.Year = int32(t.Year()) - 1900
	rtctime.Mon = int32(t.Month()) - 1
	rtctime.Mday = int32(t.Day())
	rtctime.Hour = int32(t.Hour())
	rtctime.Min = int32(t.Minute())
	rtctime.Sec = int32(t.Second())
	//fmt.Println(rtctime)

	ntt := syscall.NsecToTimeval(t.UnixNano())
	//fmt.Println(ntt)
	syscall.Settimeofday(&ntt)

	err = unix.IoctlSetRTCTime(int(f.Fd()), rtctime)
	if err != nil {
		return fmt.Errorf("setDateTime error.", t)
	}
	//t:=time.Date(int(rt.Year+1900), time.Month(int(rt.Mon)+1), int(rt.Mday), int(rt.Hour), int(rt.Min), int(rt.Sec), 0, time.UTC)
	//fmt.Printf("RTC time: %04d-%02d-%02d %02d:%02d:%02d", v.Year+1900, v.Mon+1, v.Mday, v.Hour, v.Min, v.Sec)
	return nil
}
